package org.sjs.dreamfly.biz.movie.detail

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.lifecycle.ViewModelProvider
import com.google.common.eventbus.Subscribe
import kotlinx.coroutines.launch
import org.sjs.dreamfly.R
import org.sjs.dreamfly.app.PlayInfoLoadedEvent
import org.sjs.dreamfly.app.defaultEventBus
import org.sjs.dreamfly.biz.movie.MovieConstants
import org.sjs.dreamfly.browser.BrowserConst
import org.sjs.dreamfly.browser.PhemonWebView
import org.sjs.dreamfly.common.base.BaseActivity
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.common.util.Router
import org.sjs.dreamfly.data.Config
import org.sjs.dreamfly.model.ModelUtils
import org.sjs.dreamfly.model.MovieInfo
import org.sjs.dreamfly.player.MoviePlayerFragment
import org.sjs.dreamfly.player.PlayerFragment

class MovieDetailActivity : BaseActivity(), MovieDetailFragment.ViewClickListener {

    private lateinit var viewModel: MovieDetailViewModel
    private lateinit var webView: PhemonWebView
    private var detailFragment: MovieDetailFragment? = null
    private var playFragment: MoviePlayerFragment? = null
    private var channelType = Config.defaultChannelType4XiGua
    private lateinit var sniffStatus: MovieDetailViewModel.SniffStatus

    override fun onCreate(savedInstanceState: Bundle?) {
        intent.getStringExtra(Router.KEY_CHANNEL_TYPE)?.let {
            channelType = it
        }
        super.onCreate(savedInstanceState)
        defaultEventBus.register(this)
    }
    override fun onDestroy() {
        super.onDestroy()
        defaultEventBus.unregister(this)
    }
    override fun requireLayoutId(): Int {
        return R.layout.activity_movie_detail
    }
    override fun onInitViewModel() {
        viewModel = ViewModelProvider(this).get(MovieDetailViewModel::class.java)
        sniffStatus = viewModel.useSniffStatus(channelType)
        viewModel.setVideoUrlLoadDelegate {
            webView.inject(it, BrowserConst.InjectMethod.METHOD_PLAY_INFO,
                BrowserConst.InjectPoint.POINT_ON_PROGRESS_MORE_THAN_1)
            sniffStatus.toBegin()
        }
    }

    override fun onLoadData(savedInstanceState: Bundle?, newIntent: Intent?) {
        (newIntent ?: intent).let { it ->
            it.getStringExtra(Router.KEY_MOVIE_INFO)?.let {json ->
                mainScope.launch {
                    viewModel.onMovieLoaded(MovieInfo.fromJson(json))
                    title = viewModel.getMovieInfo()?.name
                    if (!viewModel.isPlayListPrepared()) {
                        viewModel.getMovieInfo()?.refer?.let {
                                url -> webView.inject(url, BrowserConst.InjectMethod.METHOD_PLAY_LIST,
                            BrowserConst.InjectPoint.POINT_ON_PROGRESS_MORE_THAN_1)
                            sniffStatus.toBegin()
                        }
                    }
                    detailFragment?.onLoadData()
                }
            }
        }
    }

    override fun onBindViews() {
        webView = findViewById(R.id.web_view)
    }

    @SuppressLint("SetTextI18n")
    override fun onInitViews() {
        hideLoadingView()
        webView.useIPhoneUserAgent()
        webView.webViewClientAcceptVisitor(object : WebViewClient() {
            override fun onLoadResource(view: WebView?, url: String?) {
                LogUtil.d("view.url:$view?ur, url:$url")
                if (ModelUtils.isXiGuaVideoUrl(url)) {
                    onEventPlayInfoLoaded(url!!, view?.url)
                    return
                }
                super.onLoadResource(view, url)
            }
        })
        if (detailFragment == null) {
            detailFragment = MovieDetailFragment().newInstance(channelType)
            detailFragment?.addListener(this)
        }
        supportFragmentManager.beginTransaction().replace(R.id.detail_fragment_stub, detailFragment!!).commitNow()
    }

    @Subscribe
    private fun onEventPlayInfoLoaded(event: PlayInfoLoadedEvent) {
        LogUtil.d(event.toString())
        onEventPlayInfoLoaded(event.videoInfo.videoUrl?:"", event.videoInfo.refer)
    }
    private fun onEventPlayInfoLoaded(url: String, refer: String?) {
        mainScope.launch {
            if (viewModel.getCurrentVideoInfo()?.videoUrl?.equals(url) == true) {
                return@launch
            }
            sniffStatus.recordPlayInfoSniffed()
            if (!sniffStatus.isSniffing()) {
                webView.loadUrl("about:blank")
            }
            viewModel.onPlayInfoLoaded(url, refer)
            if (playFragment?.isVisible == true) {
                playFragment?.resumePlay()
            }
            detailFragment?.onPlayInfoLoaded(url, refer)
        }
    }
    override fun onClick(view: View, position: Int) {
        playVideo(position)
    }
    private fun playVideo(index: Int) {
        viewModel.select(index)
        if (playFragment == null) {
            playFragment = PlayerFragment.newInstance(index)
            playFragment?.setDataProvider(viewModel)
        } else {
            playFragment?.arguments?.putInt(Router.KEY_INDEX, index)
        }
        hideTitleBar()
        if (requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }
        supportFragmentManager.beginTransaction().replace(R.id.player_view_stub, playFragment!!).commitNow()
    }
}
